package com.atguigu.edu.service.impl;

import com.atguigu.edu.entity.Video;
import com.atguigu.edu.feign.VodClient;
import com.atguigu.edu.mapper.VideoMapper;
import com.atguigu.edu.service.VideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author Rayyy666
 * @since 2022-04-02
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private VodClient vodClient;

    /**
     * 根据课程ID删除小节 同时删除小节里的课程视频
     *
     * @param courseId
     */
    @Override
    public void removeVideoByCourseId(String courseId) {
        //1.根据课程ID查询出所有的 课程视频ID
        QueryWrapper<Video> wrapper = new QueryWrapper<>();

        wrapper.eq("course_id", courseId);
        wrapper.select("video_source_id");//只查询指定字段的值
        List<Video> videoList = baseMapper.selectList(wrapper);

        //List<Video>变成List<String>
        ArrayList<String> videoIds = new ArrayList<>();
        for (Video video : videoList) {
            String videoSourceId = video.getVideoSourceId();
            if (!StringUtils.isEmpty(videoSourceId)) {
                //不为空放到ID集合里面去
                videoIds.add(videoSourceId);
            }
        }

        if (videoIds.size() > 0) {
            //根据多个视频ID删除阿里云视频
            vodClient.deleteBatchVideo(videoIds);
        }
        
        wrapper.eq("course_id", courseId);
        baseMapper.delete(wrapper);
    }
}
